<?php

namespace App\Http\Controllers;

use App\Models\Whitelist;
use Illuminate\Http\Request;

class WhitelistController extends Controller
{
  public function index(Request $request)
  {
    $all = Whitelist::where('user_id', auth()->id())
      ->when($request->has('type'), function ($q) use ($request) {
        $q->where('type', $request->type);
      })
      ->get();

    return success($all);
  }

  public function store(Request $request)
  {
    $request->validate([
      'list.*' => 'required|ip',
      'type' => 'required'
    ]);

    Whitelist::where('user_id', auth()->id())
      ->where('type', $request->type)
      ->delete();

    foreach ($request->list as $ip) {
      Whitelist::create([
        'ip' => $ip,
        'type' => $request->type,
        'user_id' => auth()->id()
      ]);
    }
    return success('ok');
  }

  public function update(Request $request, Whitelist $whitelist)
  {
    $request->validate([
      'ip' => 'required|ip'
    ]);

    $whitelist->ip = $request->input('ip');
    $whitelist->save();

    return success('ok');
  }

  public function destroy(Request $request)
  {
    Whitelist::where('user_id', $request->uid)->delete();
    return success('ok');
  }
}
